﻿using System;
using System.Reactive.Subjects;

///////////////////////////////////////////////////////////
//This code is taken from the Channel9 video tutorials.
//They are here for convenience - check the web link in the
//folder for each of these to see the original postings.
//
//These challenges are completed - the uncompleted ones are in
//a subfolder below this one, named OriginalCode
//////////////////////////////////////////////////////////////

namespace IntroductionToRx
{
    class Program
    {
        static void Main(string[] args)
        {
            ProcessEvents();
            ProcessObservables();
            Console.ReadLine();
        }

        private static void ProcessObservables()
        {
            Console.WriteLine("*** Observables ***");
            var myObservables = new MyObservables();

            var textChangedSubscription = myObservables.TextChanged.Subscribe(text => Console.WriteLine(text));
            myObservables.OnTextChanged("The");
            myObservables.OnTextChanged("Reactive");

            var lengthSubscription = myObservables.LengthChanged.Subscribe(length => Console.WriteLine(length));
            myObservables.OnTextChanged("Extensions");
            myObservables.OnTextChanged("are");

            textChangedSubscription.Dispose();
            myObservables.OnTextChanged("compositional");

            lengthSubscription.Dispose();

            myObservables.OnTextChanged("!");
        }

        private static void ProcessEvents()
        {
            Console.WriteLine("*** Events ***");
            var myEvents = new MyEvents();

            //must declare them like this in order to unsubscribe
            Action<string> textHandler = text => Console.WriteLine(text);
            Action<int> lengthHandler = length => Console.WriteLine(length);

            myEvents.TextChanged += textHandler;
            myEvents.OnTextChanged("The");
            myEvents.OnTextChanged("Reactive");

            myEvents.LengthChanged += lengthHandler;
            myEvents.OnTextChanged("Extensions");
            myEvents.OnTextChanged("are");

            myEvents.TextChanged -= textHandler;
            myEvents.OnTextChanged("compositional");

            myEvents.LengthChanged -= lengthHandler;

            myEvents.OnTextChanged("!");
        }
    }
}
